/** @format */

import {AxiosInterceptorManager, RejectedFn, ResolvedFn} from '../types/index';

interface Interceptor<T> {
  resolved: ResolvedFn<T>;
  rejected?: RejectedFn;
}

export default class InterceptorManager<T> implements AxiosInterceptorManager<T> {
  private interceptors: Array<Interceptor<T> | null>;
  constructor() {
    this.interceptors = [];
  }

  use(resolved: ResolvedFn<T>, rejected?: RejectedFn): number {
    this.interceptors.push({
      resolved,
      rejected,
    });
    return this.interceptors.length - 1; // 返回拦截器的id(数组index)
  }

  forEach(fn: (interceptor: Interceptor<T>) => void): void {
    this.interceptors.forEach(interceptor => {
      if (interceptor) {
        fn(interceptor);
      }
    });
  }

  eject(id: number): void {
    if (this.interceptors[id]) {
      this.interceptors[id] = null; // 不要splice删除，因为后面id都会乱
    }
  }
}
